<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\library\Token;
use app\common\model\card\Entitylog;
use app\common\model\Member;
use app\common\model\Merchant;
use app\common\model\Merchantuser;
use app\common\model\Order;
use app\common\model\Regionservice;
use app\common\model\Regionserviceuser;
use app\common\model\Washlog;
use Exception;
use fast\Random;
use think\Db;
use think\Log;
use think\Validate;

/**
 * 登录接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['checkOpenid','merchantLogin', 'merchantRego', 'regionserviceLogin', 'regionserviceRego', 'distributorRego', 'wxlogin', 'send', 'resetPassword', 'distributorRego', 'distributorLogin', 'dealerRego', 'dealerLogin'];
    protected $noNeedRight = ['*'];
    //2023-10-8  start
    /**
     * 用户openid查找用户是否存在
     * */
    public function checkOpenid()
    {
        $validate = new \think\Validate([
            ['code', 'require', 'code不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $code = $this->request->param("code");
        $result = getOpenid($code);
        /*$result["openid"]="oTE855L_jWxhgpLuOhGLpjUQTsps";
        $result["session_key"]="RUalAe+aSL7Axm0Q4gv9Ug==";*/
        if (!isset($result['openid'])) {
            $this->error('请求错误', $result);
        }
        //Log::record("111".json_encode($result));
        $model = new Member();
        $member=$model->where(["openid"=>$result['openid']])->find();
        //Log::record("sss".json_encode($member));
        if (!empty($member)){
            if ($member->status != 1) {
                $this->setError("账号已被禁用");
                return false;
            }
            if(empty($member["unionid"])){
                $member->save(["unionid"=>$result["unionid"]]);
            }
            $ret = $this->auth->direct($member["id"],0);
            if ($ret) {
                $user = $this->auth->getUserinfo();
                $user["nickname"] = $model->emoji_decode($user["nickname"]);
                $token = $user["token"];
                $user["token"] = $token;
                $user["wxopenid"] = $member["wxopenid"]?1:'';
                $this->success("登录成功", $user);
            } else {
                $this->error($this->auth->getError());
            }
            //Log::record("222".json_encode($user));
            $this->success("成功", $user);
        }else{
            $this->error("请完善用户信息",'',3);
        }
    }
    //2023-10-8  end
    /**
     * 获取用户openid
     * */
    public function wxlogin()
    {
        $validate = new \think\Validate([
            ['code', 'require', 'code不能为空'],
            ['avatar', 'require', '头像不能为空'],
            ['nickname', 'require', '昵称不能为空'],
            ['type', 'require', '类型不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        //if(!preg_match('[@_!#$%^&*()<>?/|}{~:]', $this->request->param("nickname"))) $this->error("昵称不能包含特殊字符");
        $code = $this->request->param("code");
        $result = getOpenid($code);
        /*$result["openid"]="oTE855L_jWxhgpLuOhGLpjUQTsps";
        $result["session_key"]="RUalAe+aSL7Axm0Q4gv9Ug==";*/
        if (!isset($result['openid'])) {
            $this->error('请求错误', $result);
        }
        $model = new Member();
        $data = [
            "nickname" => $model->emoji_encode($this->request->param("nickname")),
            "avatar" => $this->request->param("avatar"),
            "openid" => $result['openid'],
            "session_key" => $result['session_key'],
            "unionid" => $result['unionid'],
            "type" => $this->request->param("type"),
            "agent_id" => $this->request->param("agent_id"),
        ];
        $ret = $this->auth->login('', '', 0, $data);
        if ($ret) {
            $user = $this->auth->getUserinfo();
            $member=$model->field("wxopenid")->where(["openid"=>$result['openid']])->find();
            $user["nickname"] = $model->emoji_decode($user["nickname"]);
            $token = $user["token"];
            $user["token"] = $token;
            $user["wxopenid"] = $member["wxopenid"]?1:'';
            $this->success("登录成功", $user);
        } else {
            $this->error($this->auth->getError());
        }
        $this->success("成功", $user);
    }

    /**
     * 获取用户手机号码
     * */
    public function getWxPhone()
    {
        $tmp = getAccessToken();
        $token = $tmp["access_token"];
        $data['code'] = input('code');
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $info = \fast\Http::post($url, json_encode($data), 'json');
        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info, true);
        if ($tmpinfo["errcode"] == 0) {
            $update = ["mobile" => $tmpinfo["phone_info"]["purePhoneNumber"]];
            Member::where(["id" => $this->auth->id])->update($update);
        } else {
            $this->error($tmpinfo["errcode"]);
        }
        $this->success("成功", ["mobile" => $tmpinfo["phone_info"]["purePhoneNumber"]]);
    }

    /**
     * 商户登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function merchantLogin()
    {
        $this->login(1);
    }

    /**
     * 区域服务商登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function regionserviceLogin()
    {
        $this->login(2);
    }

    /**
     * 卡经销商登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function dealerLogin()
    {
        $this->login(3);
    }

    /**
     * 渠道分销商登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function distributorLogin()
    {
        $this->login(4);
    }

    /**
     * 登录
     * */
    private function login($type = 0)
    {
        $data = [
            ['account', 'require|regex:/^1\d{10}$/', '手机号码不能为空|手机号码格式错误'],
            ['password', 'require', '密码不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password, $type);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 商户注册
     * */
    public function merchantRego()
    {
        $data = [
            ['account', 'require|regex:/^1\d{10}$/|unique:merchantuser,mobile', '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
            ['name', 'require', '店铺名称不能为空'],
            ['logo', 'require', '店铺logo不能为空'],
            ['address', 'require', '店铺地址不能为空'],
            ['classify', 'require', '店铺地址不能为空'],
            ['door_image', 'require', '门头照片不能为空'],
            ['license_image', 'require', '营业执照不能为空'],
            ['door_contacts', 'require', '店铺联系人不能为空'],
            ['telephone', 'require', '店铺联系号码不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $user = Merchantuser::field("1")->where(["mobile" => $params["account"]])->find();
        if (!empty($user)) $this->error("该账号已存在");
        Db::startTrans();
        try {
            $user_data = [
                "is_super" => 1,
                "mobile" => $params["account"],
                "name" => $params["name"] . "超管账号",
                //"username"=>$params["account"],
                "password" => $params["password"],
            ];
            $params["mobile"] = $params["account"];
            $user_data['salt'] = Random::alnum();
            $user_data['password'] = md5(md5($user_data['password']) . $user_data['salt']);
            unset($params["account"]);
            unset($params["password"]);
            if (isset($params["regionserviceuser_id"])) {
                $regionservice = Regionserviceuser::field("id")->where(["id" => $params["regionserviceuser_id"]])->find();
                $params["regionservice_id"] = $regionservice["id"] ?? 0;
            }
            //7-18 绑定区域服务商 start
            if ($this->request->param("merchantuseruser_id") && !empty($this->request->param("merchantuseruser_id"))) {
                $regionserviceuser = Regionserviceuser::field("regionservice_id")->where(["id" => $params["merchantuseruser_id"]])->find();
                if (!empty($regionserviceuser)) {
                    $params["regionservice_id"] = $regionservice["regionservice_id"];
                } else {
                    $params["merchantuseruser_id"] = 0;
                }
            }
            //7-18 绑定区域服务商 end
            $params["createtime"] = time();
            $ret = Merchant::insertGetId($params);
            $user_data['merchant_id'] = $ret;
            Merchantuser::create($user_data);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('注册成功，请等待后台审核'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取商户和登录用户信息
     * */
    public function getMerchant()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 1) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        /*判断当前账号身份 end*/
        $user = Merchantuser::field("id,merchantuser.name,avatar,merchantuser.mobile,merchantuser.status,merchantuser.is_trila,IF(openid<>'',1,0) is_wx")
            ->with(["merchant" => function ($query) {
                $query->withField('name,logo,refer,mobile,address,lon,lat,door_image,images,license_image,
            door_contacts,telephone,money,status,remark,openswitch,account_number,account_image,start_time,end_time,classify,is_trila');
            }, "merchantpost" => function ($query) {
                $query->withField('name');
            }])
            ->where(["merchantuser.id" => $this->auth->id])
            ->find();
        if (empty($user)) $this->error("该账号或店铺不存在");
        if (!empty($user["merchant"]["images"])) $user["merchant"]["images"] = explode(",", $user["merchant"]["images"]);
        $this->success("成功", $user);
    }

    /**
     * 修改用户密码
     * */
    public function resetpwd()
    {
        $data = [
            ['old_password', 'require|regex:\S{6,30}', '旧密码不能为空|旧密码长度必须在6-30位之间，不能包含空格'],
            ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $user = $this->auth->getUser();
        if ($user["password"] != md5(md5($params['old_password']) . $user['salt'])) $this->error("旧密码错误");
        $user_data['salt'] = Random::alnum();
        $user_data['password'] = md5(md5($params['password']) . $user_data['salt']);
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        /*判断当前账号身份 end*/
        Db::startTrans();
        try {
            $user->allowField(true)->save($user_data);
            $this->auth->direct($user->id, $token["type"]);
            Token::delete($token["token"]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("修改成功");
    }

    /**
     * 区域服务商注册
     * */
    public function regionserviceRego()
    {
        $data = [
            ['account', 'require|regex:/^1\d{10}$/|unique:regionserviceuser,mobile', '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
            ['name', 'require', '服务商名称不能为空'],
            ['region', 'require', '签约区域不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $user = Regionserviceuser::field("1")->where(["mobile" => $params["account"]])->find();
        if (!empty($user)) $this->error("该账号已存在");
        $region=explode(",",$params["region"]);
        foreach ($region as $v){
            $address_rules=Regionservice::where('FIND_IN_SET("'.$v.'", region)')->where(["status"=>'1'])->find();
            if(!empty($address_rules)) $this->error($v."已存在规则");
        }
        Db::startTrans();
        try {
            $user_data = [
                "is_super" => 1,
                "mobile" => $params["account"],
                "name" => $params["name"] . "超管账号",
                //"username"=>$params["account"],
                "password" => $params["password"],
            ];
            $user_data['salt'] = Random::alnum();
            $user_data['password'] = md5(md5($user_data['password']) . $user_data['salt']);
            $params["mobile"] = $params["account"];
            unset($params["account"]);
            unset($params["password"]);
            $params["createtime"] = time();
            $ret = Regionservice::insertGetId($params);
            $user_data['regionservice_id'] = $ret;
            Regionserviceuser::create($user_data);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('注册成功，请等待后台审核'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取区域服务商和登录用户信息
     * */
    public function getRegionservice()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 2) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        /*判断当前账号身份 end*/
        $user = Regionserviceuser::field("id,regionserviceuser.name,avatar,regionserviceuser.mobile,regionserviceuser.status,promotion_code,promotion_url,IF(openid<>'',1,0) is_wx")
            ->with("regionservice")
            ->where(["regionserviceuser.id" => $this->auth->id])
            ->find();
        if (empty($user)) $this->error("该账号或区域服务商不存在");
        if (empty($user["status"])) $this->error("区域服务商审核中");
        if ($user["status"] == 2) $this->error("区域服务商已被驳回：" . $user["remark"]);
        if ($user["status"] == 3) $this->error("区域服务商已被禁用");
        /*$order=Order::where(["type_data" => '0',"regionservice_id"=>$user["regionservice"]["id"]])
            ->count();
        $goods=Washlog::where(["type_data" => '2',"regionservice_id"=>$user["regionservice"]["id"]])
            ->count();*/
        $order = Order::where(["regionservice_id" => $user["regionservice"]["id"]])
            ->whereIn("type_data", ['0', '2'])
            ->count();
        $kabaw = Washlog::where(["type_data" => '1', "regionservice_id" => $user["regionservice"]["id"]])->count();
        $user["kabaw_count"] = $kabaw;
        $user["order_count"] = $order;
        //$user["order_count"]=$order+$goods;
        $this->success("成功", $user);
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 发送验证码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send()
    {
        $mobile = $this->request->post("mobile");
        $event = $this->request->post("event");
        $event = $event ? $event : 'changepwd';
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = \app\common\model\Sms::where(["mobile" => $mobile, "event" => $event])->find();
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        $type = $this->request->param("type") ?? 1;
        //发送对象:0=用户,1=店铺,2=区域服务商,3=卡经销商,4=分销商
        if ($event) {
            if ($type == 1) {
                $userinfo = Merchantuser::getByMobile($mobile);
            }
            if ($type == 2) {
                $userinfo = Regionserviceuser::getByMobile($mobile);
            }
            if ($type == 3) {
                $userinfo = \app\common\model\card\Dealer::getByMobile($mobile);
            }
            if ($type == 4) {
                $userinfo = \app\common\model\Distributor::getByMobile($mobile);
            }
            if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $code = Random::numeric(4);
        $sms = new Sms();
        $str = [
            "code" => $code,
        ];
        Db::startTrans();
        try {
            Smslib::sendCode($mobile, $code, $event, $type);
            $ret = $sms->hairsendSms($mobile, $str);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }

    /**
     * 重置密码
     * */
    public function resetPassword()
    {
        $data = [
            ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
            ['mobile', 'require|regex:/^1\d{10}$/', '手机号码不能为空|手机号码格式错误'],
            ['code', 'require|regex:/[0-9]{4}/', '请输入4位验证码|请输入4位验证码'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $type = $this->request->param("type") ?? 1;
        //发送对象:0=用户,1=店铺,2=区域服务商,3=卡经销商,4=分销商
        if ($type == 1) {
            $user = Merchantuser::where(["mobile"=>$params["mobile"]])->find();
        }
        if ($type == 2) {
            $user = Regionserviceuser::where(["mobile"=>$params["mobile"]])->find();
        }
        if ($type == 3) {
            $user = \app\common\model\card\Dealer::where(["mobile"=>$params["mobile"]])->find();
        }
        if ($type == 4) {
            $user = \app\common\model\Distributor::where(["mobile"=>$params["mobile"]])->find();
        }
        //$user = Merchantuser::getByMobile($params["mobile"]);
        if (!$user) {
            $this->error("账号不存在");
        }
        $sms = new \app\common\library\Sms();
        $ret = $sms->check($params["mobile"], $params["code"], 'resetpwd',$type);
        if (!$ret) {
            $this->error("验证码不正确");
        }
        $res = false;
        Db::startTrans();
        try {
            $salt = Random::alnum();
            $newpassword = md5(md5($params["password"]) . $salt);
            //$res = Merchantuser::where(["id" => $user["id"]])->update(['password' => $newpassword, 'salt' => $salt]);
            $res = $user->save(['password' => $newpassword, 'salt' => $salt]);
            \app\common\library\Sms::flush($params["mobile"], 'resetpwd');
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($res) {
            $this->success("重置密码成功");
        } else {
            $this->error("修改失败");
        }
    }


    /**
     * 渠道分销商注册
     * */
    public function distributorRego()
    {
        $data = [
            ['account', 'require|regex:/^1\d{10}$/|unique:distributor,mobile', '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
            ['name', 'require', '分销商名称不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $model = new \app\common\model\Distributor();
        Db::startTrans();
        try {
            $params['salt'] = Random::alnum();
            $params['mobile'] = $params["account"];
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $params["createtime"] = time();
            $ret = $model->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('注册成功，请等待后台审核'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取渠道分销商信息
     * */
    public function getDistributor()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 4) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        /*判断当前账号身份 end*/
        $user = \app\common\model\Distributor::field("id,name,appellation,email,account_number,remark,mobile,status,money,avatar,IF(openid<>'',1,0) is_wx")
            ->where(["id" => $this->auth->id])->find();
        if (empty($user)) $this->error("该渠道分销商不存在");
        if (empty($user["status"])) $this->error("渠道分销商审核中");
        if ($user["status"] == 2) $this->error("渠道分销商已被驳回：" . $user["remark"]);
        if ($user["status"] == 3) $this->error("渠道分销商已被禁用");
        $user["order_count"] = Order::where(["agent_id" => $this->auth->id, "status" => '1', "type_data" => '1'])->count();
        $user["member_count"] = Member::where(["agent_id" => $this->auth->id])->count();
        $this->success("成功", $user);
    }

    /**
     * 卡经销商注册
     * */
    public function dealerRego()
    {
        $data = [
            ['account', 'require|regex:/^1\d{10}$/|unique:card_dealer,mobile', '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
            ['name', 'require', '卡经销商名称不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $model = new \app\common\model\card\Dealer();
        Db::startTrans();
        try {
            $params['salt'] = Random::alnum();
            $params['mobile'] = $params["account"];
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $params["createtime"] = time();
            $ret = $model->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('注册成功，请等待后台审核'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取卡经销商信息
     * */
    public function getDealer()
    {
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        if ($token["type"] != 3) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        /*判断当前账号身份 end*/
        $user = \app\common\model\card\Dealer::field("id,name,address,email,account_number,account_image,remark,mobile,status,money,avatar,IF(openid<>'',1,0) is_wx")
            ->where(["id" => $this->auth->id])->find();
        if (empty($user)) $this->error("该卡经销商不存在");
        if (empty($user["status"])) $this->error("卡经销商审核中");
        if ($user["status"] == 2) $this->error("卡经销商已被驳回：" . $user["remark"]);
        if ($user["status"] == 3) $this->error("卡经销商已被禁用");
        $user["order_count"] = Order::where(["agent_id" => $this->auth->id, "status" => '1', "type_data" => '1'])->count();
        $user["exchange_count"] = Entitylog::where(["card_dealer_id" => $this->auth->id, "transfer_data" => '1', "status" => '1'])->count();
        $this->success("成功", $user);
    }


    /**
     * 获取用户openid
     * */
    public function getOpenid(){
        $appid="wx64d13e22fd555473";
        $key="8fa5215c227de9d52eda3c58a79e7a11";
        if(!$this->request->param("code")) $this->error("code为空");
        $code=$this->request->param("code");
        if ($code) {
            //初始化
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$key&code=$code&grant_type=authorization_code");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);
        }
        $oauth2 = json_decode($output,true);
        //如果code失效重新获取
        if(empty($oauth2["access_token"])){
            /*$urls ="http://".$_SERVER['SERVER_NAME']."/index/weixin/index?qrcode=".$_GET['state'];
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$urls'";
            echo "</script>";*/
            $this->error("code失效");
        }
        $access_token = $oauth2["access_token"];
        //openid
        $openid = $oauth2['openid'];
        $user=$this->auth->getUser();
        $user->save(["openid"=>$openid]);
        $this->success("成功");
    }
    /**
     * 获取用户公众号openid
     * */
    public function getwxOpenid(){
        $appid="wx64d13e22fd555473";
        $key="8fa5215c227de9d52eda3c58a79e7a11";
        if(!$this->request->param("code")) $this->error("code为空");
        $code=$this->request->param("code");
        //$code="0813vrFa1VLMbG0gyiIa1zp9w523vrFl";
        if ($code) {
            //初始化
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$key&code=$code&grant_type=authorization_code");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);
        }
        $oauth2 = json_decode($output,true);
        //Log::log("ss111".json_encode($oauth2));
        //如果code失效重新获取
        if(empty($oauth2["access_token"])){
            /*$urls ="http://".$_SERVER['SERVER_NAME']."/index/weixin/index?qrcode=".$_GET['state'];
            echo "<script language='javascript' type='text/javascript'>";
            echo "window.location.href='$urls'";
            echo "</script>";*/
            $this->error("code失效");
        }
        $access_token = $oauth2["access_token"];
        //openid
        $user=Member::where(["id"=>$this->auth->id])->find();
        $openid = $oauth2['openid'];
        //$user=$this->auth->getUser();
        $user->save(["wxopenid"=>$openid]);
        $this->success("成功");
    }
}
